#include <iostream>
#include <fstream>
#include <strstream>

using namespace std;

/**
 * 文件流和字符串流
 * 输入和输出缓冲区就是字符串流对象
 *
 *
 * @return
 */
struct Student {
    char name[10];
    int num;
};

int main() {
    /**
     * 字符串流类没有open成员函数，通过调用构造函数建立字符串流对象
     *
     *  ostrstream::ostrstream(char *buffer, int n, int mode=ios::out);
     *  buffer是指向字符串数组首元素的指针
     *  n为制定的流缓冲区的大小（一般选与字符数组的大小相同，也可以不同）
     *  mode指操作方式，默认为ios::out方式
     *
     * char name[20];
         ostrstream out(name, 20);
     *
     */


    /**
     *
     * char s[20];
        istrstream str(s, 20); //不指定缓冲区的大小的话会把所有全部数据作为输入字符串流的内容
     *
     */
    Student stu[3] = {
            {"Li",    1001},
            {"Zhang", 1002},
            {"Wang",  1003}
    };
    char c[50];
    ostrstream strout1(c, 30);
    for (int i = 0; i < 3; ++i) {
        strout1 << stu[i].num << stu[i].name;
    }
    strout1 << ends; //插入一个'\0'
    cout << "array c:" << c << endl;

    ostrstream strout2(c, 40);
    for (int i = 0; i < 3; ++i) {
        strout2 << stu[i].num << " " << stu[i].name << " ";
    }
    strout2 << ends;
    cout << "array c:" << c << endl;




    //以字符串流为中介交换数据
    char c1[50] = "12 235 13 9 6 4 51 35 14 3";
    int a[10];
    cout << "array c1:" << c1 << endl;
    istrstream strin(c1, sizeof(c1));
    for (int i = 0; i < 10; ++i) {
        strin >> a[i];
    }
    cout << "array a:";
    for (int i = 0; i < 10; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
    //冒泡排序
    int j = 10, flag = 1;
    while (j > 0 && flag == 1) {
        flag = 0;
        for (int i = 0; i < j - 1; ++i) {
            if (a[i] > a[i + 1]) {
                flag = 1;
                int t = a[i];
                a[i] = a[i + 1];
                a[i + 1] = t;
            }
        }
        j--;
    }
    ostrstream strout3(c1, sizeof(c1)); //a数组是经过排序之后
    for (int i = 0; i < 10; ++i) {
        strout3 << a[i] << " ";
    }
    strout3 << ends;
    cout << "array c:" << c1 << endl;

    /**
     * 字符串输出流对象是out<<...-》输入到字符数组中
     *  字符串输入流对象是in>>arr[i]->把字符数组输出到arr数组中
     *  以字符数组为中心  输入流就是读取字符数组中  输出流就是写入字符数组中
     *
     *  不需要打开关闭  但是需要ends：\0表示结束
     *
     */

    return 0;
}